package com.blu.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class UploadController {
	
	@RequestMapping(value = "/uploadToWindows", method = RequestMethod.POST)
	public void upload(@RequestParam("file") MultipartFile[] files,@RequestParam("dirname") String dirname, HttpServletRequest request, HttpServletResponse response) throws IOException {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try{
			for (MultipartFile file : files){
				inputStream = file.getInputStream();
				String fileName = file.getOriginalFilename();
				//创建文件夹
				File folder = new File(dirname);
				if (!folder.exists() && !folder.isDirectory()) {
					folder.mkdirs();
				}
				outputStream = new FileOutputStream(dirname+ "/" + fileName);
				System.out.println(dirname+"/"+fileName);
				byte[] bs = new byte[1024];
				int len = -1;
				int count = 1;
				while ((len = inputStream.read(bs)) != -1) {
					outputStream.write(bs,0,len);
					count++;
					if(count%10240 == 0) {
						System.out.println("10MB");
					}
				}
			}
			response.setCharacterEncoding("UTF-8");
			//提示上传成功并刷新父窗口的用户数据
			response.getWriter().println("<script>parent.alert('上传成功');</script>");
		} catch (Exception e) {
			response.getWriter().println("<script>parent.alert('上传失败');</script>");
			e.printStackTrace();
		} finally {
			inputStream.close();
			outputStream.close();
		}
	
	}
	
	@RequestMapping(value = "/uploadToLinux", method = RequestMethod.POST)
	public void uploadToLinux(@RequestParam("file") MultipartFile[] files,@RequestParam("dirname") String dirname, HttpServletRequest request, HttpServletResponse response) throws IOException {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try{
			for (MultipartFile file : files){
				inputStream = file.getInputStream();
				String fileName = file.getOriginalFilename();
				//创建文件夹
				File folder = new File(dirname);
				if (!folder.exists() && !folder.isDirectory()) {
					folder.mkdirs();
				}
				outputStream = new FileOutputStream(dirname+ "/" + fileName);
				byte[] bs = new byte[1024];
				int len = -1;
				int count = 1;
				while ((len = inputStream.read(bs)) != -1) {
					outputStream.write(bs,0,len);
					count++;
					if(count%10240 == 0) {
						System.out.println("10MB");
					}
				}
			}
			response.setCharacterEncoding("UTF-8");
			//提示上传成功并刷新父窗口的用户数据
			response.getWriter().println("<script>parent.alert('上传成功');</script>");
		} catch (Exception e) {
			response.getWriter().println("<script>parent.alert('上传失败');</script>");
			e.printStackTrace();
		} finally {
			inputStream.close();
			outputStream.close();
		}
	
	}
	
	
	@GetMapping("myfile")
	public String getFileList(Model model, RedirectAttributes redirectAttributes) {
		String osName = System.getProperty("os.name");
		if(!osName.toLowerCase().startsWith("windows")) {
			redirectAttributes.addFlashAttribute("msg","对不起，当前服务器的操作系统不是Windows!");
			return "redirect:/errorPage";
		}
		List<String> winRoots = new ArrayList<>();
		for(File file : File.listRoots()) {
			winRoots.add(file.toString());
		}
		String myDirPath = "D:/";
		List<String> files = new ArrayList<>();
		List<String> dirs = new ArrayList<>();
		File file = new File(myDirPath);
		File tempFile;
		if(file.isDirectory()) {
			String[] fileList = file.list();
			for(String fileName : fileList) {
				tempFile = new File(myDirPath+"/"+fileName);
				if(tempFile.isDirectory()) {
					dirs.add(myDirPath+"/"+fileName);
				}
				if(tempFile.isFile()) {
					files.add(fileName);
				}
			}
		}
		model.addAttribute("winRoots", winRoots);
		model.addAttribute("currentdir", myDirPath);
		model.addAttribute("dirs", dirs);
		model.addAttribute("files", files);
		return "myFile";
	}
	
	@GetMapping("linuxfile")
	public String getLinuxFileList(Model model, RedirectAttributes redirectAttributes) {
		String osName = System.getProperty("os.name");
		if(!osName.toLowerCase().startsWith("linux")) {
			redirectAttributes.addFlashAttribute("msg","对不起，当前服务器的操作系统不是Linux!");
			return "redirect:/errorPage";
		}
		String myDirPath = "/usr";
		List<String> files = new ArrayList<>();
		List<String> dirs = new ArrayList<>();
		File file = new File(myDirPath);
		File tempFile;
		if(file.isDirectory()) {
			String[] fileList = file.list();
			for(String fileName : fileList) {
				tempFile = new File(myDirPath+"/"+fileName);
				if(tempFile.isDirectory()) {
					dirs.add(myDirPath+"/"+fileName);
				}
				if(tempFile.isFile()) {
					files.add(fileName);
				}
			}
		}
		model.addAttribute("currentdir", myDirPath);
		model.addAttribute("dirs", dirs);
		model.addAttribute("files", files);
		return "myLinuxFile";
	}
	
	@GetMapping("mydir")
	public String getIntoDir(Model model, @RequestParam("dirname")String dirname, RedirectAttributes redirectAttributes) {
		String osName = System.getProperty("os.name");
		if(!osName.toLowerCase().startsWith("windows")) {
			redirectAttributes.addFlashAttribute("msg","对不起，当前服务器的操作系统不是Windows!");
			return "redirect:/errorPage";
		}
		List<String> winRoots = new ArrayList<>();
		for(File file : File.listRoots()) {
			winRoots.add(file.toString());
		}
		List<String> files = new ArrayList<>();
		List<String> dirs = new ArrayList<>();
		File file = new File(dirname);
		File tempFile;
		if(file.isDirectory()) {
			String[] fileList = file.list();
			for(String fileName : fileList) {
				tempFile = new File(dirname+"/"+fileName);
				if(tempFile.isDirectory()) {
					dirs.add(dirname+ "/"+ fileName);
				}
				if(tempFile.isFile()) {
					files.add(fileName);
				}
			}
		}
		
		model.addAttribute("winRoots", winRoots);
		model.addAttribute("currentdir", dirname);
		model.addAttribute("dirs", dirs);
		model.addAttribute("files", files);
		return "myFile";
	}
	
	@GetMapping("mylinuxdir")
	public String getIntoLinuxDir(Model model, @RequestParam("dirname")String dirname, RedirectAttributes redirectAttributes) {
		String osName = System.getProperty("os.name");
		if(!osName.toLowerCase().startsWith("linux")) {
			redirectAttributes.addFlashAttribute("msg","对不起，当前服务器的操作系统不是Linux!");
			return "redirect:/errorPage";
		}
		System.out.println(dirname);
		List<String> files = new ArrayList<>();
		List<String> dirs = new ArrayList<>();
		File file = new File(dirname);
		File tempFile;
		if(file.isDirectory()) {
			String[] fileList = file.list();
			for(String fileName : fileList) {
				if(!dirname.equals("/")) {
					tempFile = new File(dirname+"/"+fileName);
				}else {
					tempFile = new File("/"+fileName);
				}
				
				if(tempFile.isDirectory()) {
					dirs.add(dirname+ "/"+ fileName);
				}
				if(tempFile.isFile()) {
					files.add(fileName);
				}
			}
		}
		model.addAttribute("currentdir", dirname);
		model.addAttribute("dirs", dirs);
		model.addAttribute("files", files);
		return "myLinuxFile";
	}
	
	@GetMapping("previousdir")
	public String toPreviousDir(@RequestParam("dirname")String dirname, RedirectAttributes redirectAttributes) {
		String osName = System.getProperty("os.name");
		if(!osName.toLowerCase().startsWith("windows")) {
			redirectAttributes.addFlashAttribute("msg","对不起，当前服务器的操作系统不是Windows!");
			return "redirect:/errorPage";
		}
		String predir = dirname;
		if(dirname.lastIndexOf("/")>2) {
			predir = dirname.substring(0, dirname.lastIndexOf("/"));
		}
		return "redirect:/mydir?dirname="+ predir;
	}
	
	@GetMapping("previouslinuxdir")
	public String toPreviousLinuxDir(@RequestParam("dirname")String dirname, RedirectAttributes redirectAttributes) {
		String osName = System.getProperty("os.name");
		if(!osName.toLowerCase().startsWith("linux")) {
			redirectAttributes.addFlashAttribute("msg","对不起，当前服务器的操作系统不是Linux!");
			return "redirect:/errorPage";
		}
		String predir = dirname;
		if(dirname.lastIndexOf("/")>0) {
			predir = dirname.substring(0, dirname.lastIndexOf("/"));
		}
		if(dirname.lastIndexOf("/")==0) {
			predir = "/";
		}
		return "redirect:/mylinuxdir?dirname="+ predir;
	}
	
	@PostMapping("/blu/deleteFile")
	public String deleteWindowsFile(@RequestParam("dirname")String dirname, @RequestParam("filename")String filename, HttpSession httpSession, RedirectAttributes redirectAttributes) {
		String osName = System.getProperty("os.name");
		if(!osName.toLowerCase().startsWith("windows")) {
			redirectAttributes.addFlashAttribute("msg","对不起，当前服务器的操作系统不是Windows!");
			return "redirect:/errorPage";
		}
		String username = (String) httpSession.getAttribute("user-name");
		if(!username.equals("blu")) {
			redirectAttributes.addFlashAttribute("msg","对不起，您没有权限删除该文件！");
			return "redirect:/errorPage";
		}
		
		boolean delete = false;
		File file = new File(dirname+"/"+filename);
		if(file.exists()&&file.isFile()) {
			delete = file.delete();
		}
		if(delete) {
			return "redirect:/mydir?dirname="+dirname;
		}else {
			redirectAttributes.addFlashAttribute("msg","对不起，删除失败！");
			return "redirect:/errorPage";
		}
		
	}
	
	@PostMapping("/blu/deleteLinuxFile")
	public String deleteLinuxFile(@RequestParam("dirname")String dirname, @RequestParam("filename")String filename, HttpSession httpSession, RedirectAttributes redirectAttributes) {
		String osName = System.getProperty("os.name");
		if(!osName.toLowerCase().startsWith("linux")) {
			redirectAttributes.addFlashAttribute("msg","对不起，当前服务器的操作系统不是Linux!");
			return "redirect:/errorPage";
		}
		String username = (String) httpSession.getAttribute("user-name");
		if(!username.equals("blu")) {
			redirectAttributes.addFlashAttribute("msg","对不起，您没有权限删除该文件！");
			return "redirect:/errorPage";
		}
		boolean delete = false;
		File file = new File(dirname+"/"+filename);
		if(file.exists()&&file.isFile()) {
			delete = file.delete();
		}
		if(delete) {
			return "redirect:/mylinuxdir?dirname="+dirname;
		}else {
			redirectAttributes.addFlashAttribute("msg","对不起，删除失败！");
			return "redirect:errorPage";
		}
		
	}
	
	@PostMapping("/chooseWinRoot")
	public String chooseWinRoot(@RequestParam String winRoot) {
		String substrWinRoot = winRoot.substring(0, winRoot.indexOf('\\'))+"/";
		return "redirect:mydir?dirname="+substrWinRoot;
	}
	
}

